import time

import pygame
import random
from pygame import mixer
# 初始化pygame
pygame.init()
mixer.init()

font = pygame.font.Font(None, 36)  # 使用默认字体，大小为36

# 设置屏幕尺寸
WIDTH, HEIGHT = 480, 640
screen = pygame.display. set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("飞机大战")

# 颜色定义
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)

background_image = pygame.image.load('images/background.png').convert()

# 在类定义和游戏循环准备之前加载背景音乐
background_music = mixer.Sound('background_music.mp3')  # 假设音乐文件名为background_music.mp3
background_music.set_volume(0.3)  # 设置音乐音量，范围0.0到1.0


# 播放背景音乐，并设置为-1以循环播放
background_music_channel = background_music.play(loops=-1)

# ... [省略其它代码] ...

# 游戏循环
running = True
clock = pygame.time.Clock()
score = 0

player_alive = True

# 飞机类
class Plane(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.image.load('player.png').convert_alpha()
        self.rect = self.image.get_rect(center=(WIDTH // 2, HEIGHT - 40))
        self.velocity = pygame.Vector2(0, 0)  # 使用Vector2来存储速度
        self.bullets = pygame.sprite.Group()
        self.health = 10

    def update(self):
        self.rect.move_ip(self.velocity)  # 使用move_ip来移动rect
        self.clamp_position()  # 限制飞机位置在屏幕内

    def clamp_position(self):
        # 限制飞机在屏幕范围内
        self.rect.clamp_ip(pygame.Rect(0, 0, WIDTH, HEIGHT - 30))

    # ... [省略其它方法] ...

    def move_left(self):
        self.velocity.x = -5

    def move_right(self):
        self.velocity.x = 5

    def move_up(self):
        self.velocity.y = -5

    def move_down(self):
        self.velocity.y = 5

    def stop(self):
        self.velocity = pygame.Vector2(0, 0)  # 停止移动，速度归零

    def shoot(self):
        bullet = Bullet(self.rect.centerx, self.rect.top)
        self.bullets.add(bullet)
        all_sprites.add(bullet)

    def damage(self, amount):
        self.health -= amount
        if self.health <= 0:
            self.kill()  # 当血量耗尽时，从精灵组中移除飞机w

# 敌机类

class Enemy1(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.image.load('images/enemy1.png').convert_alpha()
        self.rect = self.image.get_rect(center=(random.randint(20, WIDTH - 20), 0))
        self.speed = random.randint(1, 3)

    def update(self):
        self.rect.y += self.speed
        if self.rect.bottom > HEIGHT:
            self.kill()


class Enemy2(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.image.load('images/enemy2.png').convert_alpha()
        self.rect = self.image.get_rect(center=(random.randint(20, WIDTH - 20), 0))
        self.speed = random.randint(4, 6)  # 不同的速度范围

    def update(self):
        self.rect.y += self.speed
        if self.rect.bottom > HEIGHT:
            self.kill()

    def update(self):
        self.rect.y += self.speed
        if self.rect.bottom > HEIGHT:
            self.kill()

# 子弹类
class Bullet(pygame.sprite.Sprite):
    def __init__(self, x, y):
        super().__init__()
        self.image = pygame.image.load('images/player_bullet.png').convert_alpha()
        self.rect = self.image.get_rect(center=(x, y))
        self.speed = -8

    def update(self):
        self.rect.y += self.speed
        if self.rect.y < 0:
            self.kill()

# 创建精灵组
all_sprites = pygame.sprite.Group()
enemies = pygame.sprite.Group()
plane = Plane()
all_sprites.add(plane)

# 游戏循环
running = True
clock = pygame.time.Clock()
score = 0

pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))

while running:

    plane_hits = pygame.sprite.spritecollide(plane, enemies, False)
    for hit in plane_hits:
        plane.damage(1)  # 玩家被敌机击中，扣除一定血量
        hit.kill()  # 敌机被销毁
        if plane.health <= 0:
            running = False  # 血量耗尽，游戏结束
            
            game_over_font = pygame.font.Font(None, 60)  # 使用默认字体，大小为60
            game_over_text = game_over_font.render("GAME OVER", True, (255, 255, 255))  # 白色文本
            game_over_rect = game_over_text.get_rect(center=(240, 320))  # 居中放置文本
            screen.blit(game_over_text, game_over_rect)
            pygame.display.flip()  # 更新屏幕显示
            time.sleep(5)


    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_w:
                plane.move_up()
            elif event.key == pygame.K_s:
                plane.move_down()
            elif event.key == pygame.K_a:
                plane.move_left()
            elif event.key == pygame.K_d:
                plane.move_right()
            elif event.key == pygame.K_SPACE:
                plane.shoot()
        elif event.type == pygame.KEYUP:
            if event.key in (pygame.K_w, pygame.K_s, pygame.K_a, pygame.K_d):
                plane.stop()  # 当释放移动键时停止移动
    if not running:
        background_music_channel.stop()  # 停止播放背景音乐

        break  # 跳出游戏循环



    # 生成敌机
    if random.random() < 0.02:
        enemy_type = random.choice([Enemy1, Enemy2])  # 随机选择敌机类型
        enemy = enemy_type()  # 创建敌机实例
        all_sprites.add(enemy)
        enemies.add(enemy)

    all_sprites.update()



    enemy_hits = pygame.sprite.groupcollide(plane.bullets, enemies, True, True)
    for hit in enemy_hits:
        score += 1
          # 玩家被击中时减血，此处为了演示改为玩家击中敌机也减血
        if plane.health <= 0:
            running = False  # 血量耗尽，游戏结束

    screen.fill((0, 0, 0))
    screen.blit(background_image, (0, 0))  # 绘制背景图片
    all_sprites.draw(screen)
    #pygame.display.flip()

    # 显示得分和血条


    font = pygame.font.Font(None, 36)
    score_text = font.render("Score: {}".format(score), 1, WHITE)
    health_text = font.render("Health: {}".format(plane.health), 1, WHITE)
    screen.blit(score_text, (10, 10))
    screen.blit(health_text, (10, 50))

    pygame.display.flip()

    clock.tick(60)

pygame.quit()